#include "ServerSocket.h"

ServerSocket::ServerSocket(int port)
    : m_port(port) {}

ServerSocket::~ServerSocket()
{
    stop();
}

bool ServerSocket::start()
{
    m_serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (m_serverSocket == -1)
    {
        logMessage("Failed to create socket!");
        return false;
    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(m_port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int res = bind(m_serverSocket, (struct sockaddr *)&addr, sizeof(addr));
    if (res == -1)
    {
        logMessage("bind: " + std::to_string(m_port) + " port failed!");
        return false;
    }
    logMessage("bind: " + std::to_string(m_port) + " port successful!");

    listen(m_serverSocket, 128);

    // 创建接收数据的线程
    m_receiveThread = std::thread(&ServerSocket::receiveData, this);

    return true;
}

void ServerSocket::stop()
{
    m_stopThreads = true; // 设置停止标志

    if (m_clientSocket != -1)
    {
        close(m_clientSocket);
        m_clientSocket = -1;
    }
    if (m_serverSocket != -1)
    {
        close(m_serverSocket);
        m_serverSocket = -1;
    }

    // 等待线程结束
    if (m_receiveThread.joinable())
    {
        m_receiveThread.join();
    }
}

bool ServerSocket::acceptClient()
{
    struct sockaddr_in cliaddr;
    socklen_t clilen = sizeof(cliaddr);
    m_clientSocket = accept(m_serverSocket, (struct sockaddr *)&cliaddr, &clilen);
    if (m_clientSocket == -1)
    {
        logMessage("Accpet client failed!");
        return false;
    }
    logMessage("Accpet client succeeded!");

    char ip[INET_ADDRSTRLEN]; // INET_ADDRSTRLEN is defined in <netinet/in.h>
    inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, ip, INET_ADDRSTRLEN);
    std::cout << "Client's IP address: " << ip << ", Port: " << ntohs(cliaddr.sin_port) << std::endl;

    std::string ConnectionStatus = "已连接";
    std::vector<uint8_t> encodedData = EncodeMessage(Socket_Flag, ConnectionStatus);
    send(m_clientSocket, encodedData.data(), encodedData.size(), 0);

    return true;
}

bool ServerSocket::sendData(const std::string &data)
{
    if (m_clientSocket == -1)
    {
        // 客户端未连接
        return false;
    }
    send(m_clientSocket, data.data(), data.size(), 0);
    return true;
}

void ServerSocket::receiveData()
{
    while (!m_stopThreads)
    {
        char buffer[2048];
        memset(buffer, 0, sizeof(buffer));
        ssize_t bytesReceived = read(m_clientSocket, buffer, sizeof(buffer));
        if (bytesReceived > 0)
        {
            m_receivedDataBuffer.insert(m_receivedDataBuffer.end(), buffer, buffer + bytesReceived);
            std::vector<Message> messages = DecodeMessage(m_receivedDataBuffer);
            std::lock_guard<std::mutex> lock(m_mutex); // 加锁
            for (auto data : messages)
            {
                m_messages.push(data);
            }
        }
        else if (bytesReceived == 0)
        {
            logMessage("Port " + std::to_string(m_port) + " Client disconnected...");
        }
        else
        {
            logMessage("Port " + std::to_string(m_port) + " Client read....");
        }
    }
}

Message ServerSocket::readData()
{
    std::lock_guard<std::mutex> lock(m_mutex); // 加锁
    if (!m_messages.empty())
    {
        Message message = m_messages.front();
        m_messages.pop(); // 出队
        return message;
    }
    else
    {
        // 如果队列为空，则返回一个空消息或者抛出异常
        // 这里简单地返回一个空消息
        return Message();
    }
}

bool ServerSocket::getStopThreads()
{
    return m_stopThreads;
}

int &ServerSocket::getClientSocket()
{
    return m_clientSocket;
}

void UpperComputerProcessing(ServerSocket &UpperComputer)
{
    while (!UpperComputer.getStopThreads())
    {
        Message message = UpperComputer.readData();
        MessageProcessor(message);
    }
}
